package com.chinanet.utils.file;

import com.chinanet.config.FileStorageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class FileStorageService {

    private final Path fileStorageLoaction;

    @Autowired
    public FileStorageService(FileStorageProperties fileStorageProperties) {
        this.fileStorageLoaction = Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize();

        try {
            // Java 7 新特征
            Files.createDirectories(this.fileStorageLoaction);
        } catch (Exception e) {
            throw new FileStorageException("Could not create the directory where the uploaded files will be stored", e);
        }
    }

    public String storeFile(MultipartFile file) {
        // Normailze file name
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            if (fileName.contains("..")) {
                throw new FileStorageException("Sorry! Filename contains invalid path sequence" + fileName);
            }
            // Copy file to the target loaction (Replacing existing file with the same name
            Path targetLoaction = this.fileStorageLoaction.resolve(fileName);
            Files.copy(file.getInputStream(), targetLoaction, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
            throw new FileStorageException("Could not store file " + fileName + ". Please try again!",e);
        }
        return fileName;
    }


    public Resource loadFileAsResource(String fileName) {
        try {
        Path filePath= this.fileStorageLoaction.resolve(fileName).normalize();
        Resource resource= null;
            resource = new UrlResource(filePath.toUri());
        if(resource.exists()){
            return resource;
        }else{
            throw new MyFileNotFoundException("File not found" +fileName);
        }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new MyFileNotFoundException("File not found" + fileName,e);
        }
    }
}
